package com.group3.utils;/**
 * DownloadUtil
 *
 * @author HY
 * 2021/07/17 10:43
 **/


import com.group3.config.MyControllerAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Description 文件下载工具类
 * @author 余久
 * @Date 2021/07/17 10:43
 **/


public class DownloadUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(DownloadUtil.class);

    public static void Download(Resource resource, HttpServletRequest request, HttpServletResponse response) {
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException e) {
            LOGGER.error("无法获取文件类型", e);
        }
        String fileCode = null; // 文件名称的编码
        InputStream in = null;
        OutputStream out = null;
        String filename = resource.getFilename();
        try {
            response.reset();
            fileCode = new String(filename.getBytes("Gb2312"), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileCode); // 设置文件头
            File file = resource.getFile();
            in = new FileInputStream(file);
            int len;
            byte[] buffer = new byte[1024];
            out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != out) {
                    out.close();
                }
                if(null != in){
                    in.close();
                }
            } catch (IOException var3) {
                LOGGER.error(var3.getMessage(), var3);
            }
        }
    }
}
